package com.easyfun.healthmagicbox.comm.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;


public abstract class AbstractListJsonWrapper<T extends JsonWrapper, E> extends
		AbstractJsonWrapper<T, E> {
	List<E> mpps;

	public List<E> getMpps() {
		return mpps;
	}
	
	public AbstractListJsonWrapper(List<E> pps) {
		mpps = pps;
	}
	
	public AbstractListJsonWrapper()
	{
		
	}
	@Override
	public void deserialize(String serializedObj) throws JSONException {

		if (mpps == null) {
			mpps = new ArrayList<E>();
		}
		int begin = 0;
		int end = serializedObj.length();
		// remove [ and ]
		if (serializedObj.charAt(0)=='[')
			serializedObj = serializedObj.substring(begin + 1, end - 1);

		
		//two paths
		//
		String[] ss = serializedObj.split("\\}\\,\\{");
		int i = 0;
		if (ss.length == 1)
		{
			//{{"suggestion":"a"}}
			if (ss[0].charAt(0)=='{')
			{
				JSONObject obj = new JSONObject(ss[0]);
				deserializeFromObj(obj);
			}else
			{
				throw new JSONException(serializedObj);
			}
		}else
		{
			//{{"suggestion":"a"},{"suggestion":"b"}}
			while (i < ss.length) {
				String temp = ss[i];
				if (i == 0) {
					temp = temp + "}";
				} else if ((i > 0) && (i < ss.length - 1)) {
					temp = "{" + temp + "}";
				} else if (i == ss.length - 1) {
					temp = "{" + temp;
				}
				
				if (temp.charAt(0)=='{')
				{
					JSONObject obj = new JSONObject(temp);
					deserializeFromObj(obj);
				}else
				{
					break;
				}
				
				i++;
			}
		}
		
	}

}
